let id = location.href.split('?')[1].split('=')[1];
console.log(id);

let rolename = document.querySelector('.rolename'),
    cover = document.querySelector('.cover'),
    description = document.querySelector('.description'),
    roletype_select = document.querySelector('.roletype'),
    game_select = document.querySelector('.game'),
    gender_radios = document.querySelectorAll('.gender')

const getroletypes = async() => {
    try {
        let response = await ajax('getroletypes?pagenum=1&pagesize=20')
        let roleltypes = response.data
        roletype_select = document.querySelector('.roletype')
        for (const roleltype of roleltypes) {
            let option = document.createElement('option')
            option.innerHTML = roleltype.roletypename
            option.value = roleltype.id
            roletype_select.add(option)
        }
    } catch (error) {
        alert(error.meta.msg)
    }
}

const getgames = async() => {
    try {
        let response = await ajax('getgames?pagenum=1&pagesize=20')
        let games = response.data
        game_select = document.querySelector('.game')
        for (const game of games) {
            let option = document.createElement('option')
            option.innerHTML = game.gamename
            option.value = game.id
            game_select.add(option)
        }
    } catch (error) {
        alert(error.meta.msg)
    }
}

// const perviewimg = () => {
//     let cover = _this.value
//     if (cover) {
//         document.querySelector('.cover_img').src = cover
//     }
// }

const get_onerole = async() => {
    try {
        const response = await ajax(`get_onerole?id=${id}`)
        let role = response.data[0]
        rolename.value = role.rolename
        cover.value = role.cover
        description.value = role.description
            // 赋值下拉框
        copyright_select.value = role.roletype
        type_select.value = role.game
        for (const radio of gender_radios) {
            if (radio.value == role.gender) radio.checked = true
        }
        // if (cover) {
        //     cover_img.src = role.cover
        // }
    } catch (error) {
        alert(error.meta.msg)
    }
}

const update_role = async() => {
    let rolename1 = rolename.value,
        cover1 = cover.value,
        description1 = description.value
    let gender,
        roletype = roletype_select.value,
        game1 = game_select.value

    for (const radio of gender_radios) {
        if (radio.checked) {
            gender = radio.value
        }
    }
    let obj = {
        id,
        rolename: rolename1,
        cover: cover1,
        roletype,
        game: game1,
        description: description1,
        gender,
    }
    const response = await ajax('updaterole', 'PUT', obj)
    alert(response.msg)
    location.href = './roles.html'
}

window.onload = function() {
    getroletypes()
    getgames()
    get_onerole()
}